{% extends "layout.html" %}
{% set active_page = "dashboard" %}
{% set help_page = ["https://kizniche.github.io/Mycodo/Data-Viewing/#dashboard", dict_translation['dashboard']['title']] %}

{% set dashboard_dict = dict() %}

{% block title %} - {% for each_dash in dashboards if each_dash.unique_id == dashboard_id %}{{each_dash.name}}{% endfor %} {{dict_translation['dashboard']['title']}}{% endblock %}

{% block head %}
  <script>
  let widget = [];
  </script>

  <link href="/static/css/toastr.min.css" rel="stylesheet"/>
  <script type="text/javascript" src="/static/js/toastr.min.js"></script>

  <link rel="stylesheet" href="/static/css/gridstack.css" />
  <link rel="stylesheet" href="/static/css/gridstack-custom.css" />
  <script src="/static/js/gridstack-all.js"></script>

  {% for widget_type, file_head in list_html_files_head.items() %}
  <!-- Widget {{widget_type}} widget_dashboard_head template begin -->
  {% include 'user_templates/{}'.format(file_head) %}
  <!-- Widget {{widget_type}} widget_dashboard_head template end -->
  {% endfor %}

  <script>
    // Return timestamp from epoch (used in multiple widgets)
    function epoch_to_timestamp(epoch) {
      const date = new Date(parseFloat(epoch));
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = "0" + date.getMinutes();
      const seconds = "0" + date.getSeconds();
      return month + "/" + day + " " + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
    }
  </script>
{% endblock %}

{% block body %}
  <!-- Route: /dashboard -->
  <div class="container">
  {% include 'flash_messages.html' %}
  </div>

  <div class="container-fluid">

    <div class="grid-stack">
    {% for each_widget in table_widget.query.filter(table_widget.dashboard_id == dashboard_id).all() -%}
      <div id="gridstack_widget_{{each_widget.unique_id}}"
        class="grid-stack-item"
      {% if this_dashboard.locked %}
        gs-no-move="yes"
        gs-no-resize="yes"
      {% endif %}
        gs-id="{{each_widget.unique_id}}"
        gs-x="{{each_widget.position_x}}"
        gs-y="{{each_widget.position_y}}"
        gs-w="{{each_widget.width}}"
        gs-h="{{each_widget.height}}">
        {% include 'pages/dashboard_entry.html' %}
      </div> <!-- grid-stack-item -->
    {%- endfor -%}
    </div> <!-- grid-stack -->

    <hr/>
  </div>

  <div style="clear: both"></div>

  {% if not this_dashboard.locked %}

  <div class="container-fluid" style="padding-bottom: 1em">

    <div class="form-inline" style="padding-bottom: 1em;">
      <div class="form-group">
        {{form_base.widget_type(class_='selectpicker', **{'data-style': 'btn btn-sm btn-primary'})}}
      </div>
    </div>

    {% for each_widget in dict_widgets %}

      {% set dict_options = dict_widgets[each_widget] %}
      {% set custom_options_values = [] %}
      {% set force_default_value = true %}

    <div class="add_dashboard_widget" style="display: none" id="{{each_widget}}">
      <form method="post" id="add_widget_form" action="/dashboard/{{dashboard_id}}">
      {{form_base.csrf_token}}
      <input type="hidden" name="dashboard_id" value="{{dashboard_id}}">
      <input type="hidden" name="widget_type" value="{{each_widget}}">

      <div class="form-row small-gutters">
        {% include 'pages/dashboard_options/TEMPLATE_OPTIONS_WIDGET_ADD.html' %}
      </div>

      {% if 'custom_options' in dict_widgets[each_widget] %}
      <div class="row small-gutters" style="padding: 0.5em">
        <div class="col-12">
          <h5>{{_('Custom Options')}}</h5>
        </div>
        {% if 'custom_options_message' in dict_options %}
          {% include 'pages/form_options/Custom_Options_Message.html' %}
        {% endif %}
        {% for each_option in dict_widgets[each_widget]['custom_options'] %}
          {% include 'pages/form_options/Custom_Options.html' %}
        {% endfor %}
      </div>
      {% endif %}

      <div class="form-inline btn-group" style="padding: 1em 0 1em 0">
        <div class="form-group">
          {{form_base.widget_add(class_='btn btn-primary')}}
        </div>
      </div>

      </form>
    </div>

    {% endfor %}

  </div>

  {% endif %}

<script type="text/javascript">
  // Dashboard Grid
  let options = {
    cellHeight: {{misc.grid_cell_height}},
    column: 24,
    resizable: {
      handles: 'se, sw'
    },
    draggable: {
      handle: '.panel-heading'
    },
    alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
    float: false
  };
  let grid = GridStack.init(options);

  grid.on('resizestop', function(event, elem) {
    const widget_id = $(elem).attr('gs-id');
    if (typeof widget !== "undefined" && widget_id in widget && typeof widget[widget_id].reflow !== "undefined") {
      widget[widget_id].reflow();
    }
  });

  {% if not this_dashboard.locked %}

  grid.on('change', function (event, items) {
    const width = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    )
    if (width > 768) {
      $.ajax({
        url: "/save_dashboard_layout",
        type: "POST",
        data: JSON.stringify(grid.save(false), null, '  '),
        contentType: "application/json; charset=utf-8",
        success: function (data) {}
      });
    }
  });

  // Show Add Dashboard Widget selector
  $('#widget_type').on('change', function () {
    let x = document.getElementsByClassName("add_dashboard_widget");
    for(let i = 0; i < x.length; i++){
      x[i].style.display = "none";
    }
    if (this.value !== '') {
      document.getElementById(this.value).style.display = "block";
      document.getElementById(this.value).scrollIntoView();
    }
  });

  {% endif %}

  {% for widget_type, file_js in list_html_files_js.items() %}
  // Widget {{widget_type}} widget_dashboard_js template begin
  {% include 'user_templates/{}'.format(file_js) %}
  // Widget {{widget_type}} widget_dashboard_js template end
  {% endfor %}

  $(document).ready(function() {
  {% for widget_type, file_js_ready in list_html_files_js_ready.items() %}
    <!-- Widget {{widget_type}} widget_dashboard_js_ready template begin -->
    {% include 'user_templates/{}'.format(file_js_ready) %}
    <!-- Widget {{widget_type}} widget_dashboard_js_ready template end -->
  {% endfor %}
  });
</script>

{% endblock %}
